package com.example.service.impl;

import com.example.domain.entity.Device;
import com.example.mapper.DeviceMapper;
import com.example.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.query.DeviceQuery;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-05-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Override
    public IPage<Device> pageQuery(DeviceQuery query, int pageNum, int pageSize) {
        Page<Device> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        if (query != null) {
            if (query.getDeviceId() != null) {
                wrapper.eq("device_id", query.getDeviceId());
            }
            if (StringUtils.hasText(query.getDeviceName())) {
                wrapper.like("device_name", query.getDeviceName());
            }
            if (StringUtils.hasText(query.getDeviceType())) {
                wrapper.eq("device_type", query.getDeviceType());
            }
            if (StringUtils.hasText(query.getManufacturer())) {
                wrapper.eq("manufacturer", query.getManufacturer());
            }
            if (query.getManufactureStartDate() != null && query.getManufactureEndDate() != null) {
                wrapper.between("manufacture_date", query.getManufactureStartDate(), query.getManufactureEndDate());
            }
            if (StringUtils.hasText(query.getWarrantyPeriod())) {
                wrapper.eq("warranty_period", query.getWarrantyPeriod());
            }
            if (StringUtils.hasText(query.getAfterSalesContact())) {
                wrapper.eq("after_sales_contact", query.getAfterSalesContact());
            }
            if (StringUtils.hasText(query.getContactPhone())) {
                wrapper.eq("contact_phone", query.getContactPhone());
            }
            if (StringUtils.hasText(query.getWarrantyDescription())) {
                wrapper.eq("warranty_description", query.getWarrantyDescription());
            }
        }
        return this.page(page, wrapper);
    }

    @Override
    public boolean updateDeviceStatus(Integer deviceId, String status) {
        Device device = this.getById(deviceId);
        if (device == null) {
            return false; // Or throw an exception, depending on desired behavior
        }
        device.setStatus(status);
        return this.updateById(device);
    }
}
